//
//  LGCancerTemperatureController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/8/1.
//  癌症-居家监测-体温、血氧、体重

#import "LGCancerPatientChartController.h"
#import "LGMonitoringHistoryView.h"
#import "LGCancerPatientChart.h"
#import "LGCancerMonitorHeader.h"
#import "LGCancerMonitorOxygenHeader.h"
#import "LGCancerMonitorTemperatureHeader.h"
#import "LGChartDetailAlertView.h"
//血氧
#import "LGCancerMonitorOxygenCell.h"
//体温
#import "LGCancerMonitorTemperatureCell.h"
#import "LGCancerMonitorCell.h"
#import "LGPickerView.h"
@interface LGCancerPatientChartController ()<UITableViewDelegate,UITableViewDataSource,LGCancerPatientChartDelegate>
/**   */
@property (nonatomic , strong)LGMonitoringHistoryView *historyView;
/**   */
@property (nonatomic , strong)LGCancerPatientChart *chartView;
/**   */
@property (nonatomic , strong)LGChartDetailAlertView *alertView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *footerView;
/**   */
@property (nonatomic , strong)UIButton *monthBtn;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter1;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter2;
/**   */
@property (nonatomic , strong)NSMutableArray *openArray;
/**   */
@property (nonatomic , copy)NSString *monthString;
/**   */
@property (nonatomic , strong)NSArray *dataArray;

@end

@implementation LGCancerPatientChartController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.monthString = [self.formatter2 stringFromDate:[NSDate date]];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.alertView];
    [self requestChartData];
    [self requestRecordData];
}

-(void)viewWillAppearAction{
    
}

-(void)requestChartData{
    [RequestUtil withPOST:self.chartAction parameters:@{@"patient_id":self.patientid,@"timeframe":@"30"} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.chartView.dayArray = returnData[@"xAxis"];
            if ([self.type isEqualToString:@"weight"]) {
                self.chartView.rangeArray = returnData[@"weightab"];
                self.chartView.dataArray = returnData[@"seriesBmi"];
            }else{
                self.chartView.rangeArray = @[];
                self.chartView.dataArray = returnData[@"series_t"];
            }
        }
    } error:^(NSError *error) {
        
    }];
}

//请求历史记录
-(void)requestRecordData{
    [RequestUtil withPOST:self.recordAction parameters:@{@"timeframe":self.monthString,@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData;
            [self.tableView reloadData];
        }
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    } error:^(NSError *error) {
        self.isfirst = NO;
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    }];
}

//选择月份
-(void)showMonthPickerView{
    NSMutableArray *yearArray = [NSMutableArray array];
    NSArray *monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    for (NSInteger i=2020; i<2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[yearArray,monthArray];
    pickerView.units = @[@"年",@"月"];
    pickerView.selectStr = [self.monthString stringByReplacingOccurrencesOfString:@"-" withString:@"|"];
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        weakSelf.historyView.monthLabel.text = [NSString stringWithFormat:@"%@年%@月",resultArray[0],resultArray[1]];
        weakSelf.monthString = [NSString stringWithFormat:@"%@-%@",resultArray[0],resultArray[1]];
        [weakSelf requestRecordData];
    };
}

//某点的详细数据 -- 体温、血氧
-(void)showAlertView:(NSDictionary *)dataDic  date:(NSString *)dateString  point:(CGPoint)point{
    NSDictionary *statusDic = @{@"0":@"",@"1":@"low",@"2":@"high",@"3":@"0"};
    NSString *title = @"手动记录";
    NSString *unit = [self.type isEqualToString:@"temperature"]?@"℃":@"%";
    
    if ([self.type isEqualToString:@"temperature"] && ![LGNSString(dataDic[@"source"]) isEqualToString:@"add"]) {
        //体温 -- 设备
        title = [NSString stringWithFormat:@"%@",dataDic[@"position"]];
        
    }else if ([self.type isEqualToString:@"oxygen"] && ![LGNSString(dataDic[@"source"]) isEqualToString:@"add"]){
        //血氧
        NSDictionary *titleDic = @{@"add":@"手动记录",@"lps":@"短测模式",@"lpl":@"连续模式"};
        title = titleDic[dataDic[@"source"]];
    }
    
    CGFloat marginX = (point.x>Screen_W/2.0)?(point.x-viewPix(180)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(180), viewPix(35)+viewPix(24));
    self.alertView.dateString = dateString;
    self.alertView.dataArray = @[@{@"icon":@"",@"title":title,@"color":@"#282828",@"score":[NSString stringWithFormat:@"%@%@",dataDic[@"value"],unit],@"status":statusDic[LGNSString(dataDic[@"status"])]}];
    self.alertView.hidden = NO;
}

//某点的详细数据 -- 体重
-(void)showWeightAlertView:(NSDictionary *)dataDic date:(NSString *)dateString point:(CGPoint)point{
    CGFloat marginX = (point.x>Screen_W/2.0)?(point.x-viewPix(140)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(140), viewPix(35)+viewPix(24));
    self.alertView.dateString = dateString;
    self.alertView.dataArray = @[@{@"icon":@"",@"title":@"体重",@"score":[NSString stringWithFormat:@"%@kg",dataDic[@"value"]] ,@"status":LGNSString(dataDic[@"status"])}];
    self.alertView.hidden = NO;
}

//选择月份
-(void)selecteMonthAction{
    NSMutableArray *yearArray = [NSMutableArray array];
    NSArray *monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    for (NSInteger i=2020; i<2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[yearArray,monthArray];
    pickerView.titleLabel.text = @"请选择月份";
    pickerView.units = @[@"年",@"月"];
    pickerView.selectStr = [self.monthString stringByReplacingOccurrencesOfString:@"-" withString:@"|"];
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        [weakSelf.openArray removeAllObjects];
        weakSelf.monthString = [NSString stringWithFormat:@"%@-%@",resultArray[0],resultArray[1]];
        [weakSelf requestRecordData];
    };
}

-(void)setMonthString:(NSString *)monthString{
    _monthString = monthString;
    NSArray *resultArray = [monthString componentsSeparatedByString:@"-"];
    [self.monthBtn setTitle:[NSString stringWithFormat:@"%@年%@月",resultArray[0],resultArray[1]] forState:UIControlStateNormal];
}

//历史记录 -- 展开、收起
-(void)openButtonAction:(UIButton *)sender{
    NSInteger index = sender.tag - 5000;
    if ([self.openArray containsObject:@(index)]) {
        [self.openArray removeObject:@(index)];
    }else{
        [self.openArray addObject:@(index)];
    }
    [self.tableView reloadData];
}

-(void)chartViewTouchesBegan{
    self.alertView.hidden = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.alertView.hidden = YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1+self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        NSArray *tempArray = [self.dataArray[section-1][@"children"] copy];
        return [self.openArray containsObject:@(section)]?tempArray.count:0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section >= 1){
        if ([self.type isEqualToString:@"temperature"]) {
            //体温
            LGCancerMonitorTemperatureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"temperatureCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSArray *tempArray = self.dataArray[indexPath.section-1][@"children"];
            cell.dataDic = tempArray[indexPath.row];
            cell.type = (indexPath.row == tempArray.count-1)?LGPositionTypeBottom:LGPositionTypeMiddle;
            return cell;
            
        }else if ([self.type isEqualToString:@"oxygen"]) {
            //血氧
            LGCancerMonitorOxygenCell *cell = [tableView dequeueReusableCellWithIdentifier:@"oxygenCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSArray *tempArray = self.dataArray[indexPath.section-1][@"children"];
            cell.dataDic = tempArray[indexPath.row];
            cell.type = (indexPath.row == tempArray.count-1)?LGPositionTypeBottom:LGPositionTypeMiddle;
            return cell;
            
        }else{
            //历史记录 -- 体重
            LGCancerMonitorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.cellType = self.type;
            NSArray *tempArray = self.dataArray[indexPath.section-1][@"children"];
            cell.dataDic = tempArray[indexPath.row];
            cell.type = (indexPath.row == tempArray.count-1)?LGPositionTypeBottom:LGPositionTypeMiddle;
            return cell;
        }
        
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section == 0){
        height = viewPix(92);
    }else if (section >= 1){
        CGFloat openHeight = [self.type isEqualToString:@"oxygen"]?viewPix(85):viewPix(75);
        height = [self.openArray containsObject:@(section)]?openHeight:viewPix(45);
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0){
        //历史记录
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(92))];
        UILabel *titleLabel = [UILabel lableWithText:@"历史记录" colorString:@"#282828" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(18), viewPix(16), viewPix(150), viewPix(25));
        [headView addSubview:titleLabel];
        UIView *iconView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(20), viewPix(64), 4, viewPix(14))];
        iconView.backgroundColor = [UIColor colorWithString:@"#77D4C6"];
        iconView.cornerRidus = 2;
        [headView addSubview:iconView];
        [headView addSubview:self.monthBtn];
        UIImageView *tipView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTipDown"]];
        [headView addSubview:tipView];
        [self.monthBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconView.mas_right).offset(viewPix(12));
            make.centerY.equalTo(iconView);
            make.width.equalTo(@(viewPix(110)));
            make.height.equalTo(@(viewPix(30)));
        }];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.right.equalTo(self.monthBtn);
            make.width.height.equalTo(@(16));
        }];
        return headView;
        
    }else if (section >= 1){
        //记录 -- 区头
        CGFloat openHeight = [self.type isEqualToString:@"oxygen"]?viewPix(85):viewPix(75);
        CGFloat height = [self.openArray containsObject:@(section)]?openHeight:viewPix(45);
        if ([self.type isEqualToString:@"temperature"]) {
            //体温
            LGCancerMonitorTemperatureHeader *headView = [[LGCancerMonitorTemperatureHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
            headView.openBtn.tag = 5000+section;
            headView.openBtn.selected = [self.openArray containsObject:@(section)]?YES:NO;
            [headView.openBtn addTarget:self action:@selector(openButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            headView.dateLabel.text = LGNSString(self.dataArray[section-1][@"record_date"]);
            return headView;
            
        }else if ([self.type isEqualToString:@"oxygen"]){
            //血氧
            LGCancerMonitorOxygenHeader *headView = [[LGCancerMonitorOxygenHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
            headView.openBtn.tag = 5000+section;
            headView.openBtn.selected = [self.openArray containsObject:@(section)]?YES:NO;
            [headView.openBtn addTarget:self action:@selector(openButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            headView.dateLabel.text = LGNSString(self.dataArray[section-1][@"record_date"]);
            return headView;
            
        }else{
            //体重
            LGCancerMonitorHeader *headView = [[LGCancerMonitorHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
            headView.type = self.type;
            headView.openBtn.tag = 5000+section;
            headView.openBtn.selected = [self.openArray containsObject:@(section)]?YES:NO;
            [headView.openBtn addTarget:self action:@selector(openButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            headView.dateLabel.text = LGNSString(self.dataArray[section-1][@"record_date"]);
            return headView;
        }
    }
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section >= 1){
        height = [self.openArray containsObject:@(section)]?0.01:viewPix(15);
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section >= 1){
        CGFloat height = [self.openArray containsObject:@(section)]?0.01:viewPix(15);
        LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
        footView.bottomMargin = viewPix(8);
        return footView;
    }
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, self.view.bounds.size.height);
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGCancerMonitorCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[LGCancerMonitorOxygenCell class] forCellReuseIdentifier:@"oxygenCell"];
        [_tableView registerClass:[LGCancerMonitorTemperatureCell class] forCellReuseIdentifier:@"temperatureCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.chartView;
    }
    return _tableView;
}

-(LGCancerPatientChart *)chartView{
    if(!_chartView){
        CGFloat height = [self.type isEqualToString:@"weight"]?viewPix(335):viewPix(370);
        _chartView = [[LGCancerPatientChart alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
        _chartView.type = self.type;
        _chartView.delegate = self;
    }
    return _chartView;
}

-(LGChartDetailAlertView *)alertView{
    if(!_alertView){
        _alertView = [[LGChartDetailAlertView alloc] initWithFrame:CGRectMake(0, 0, viewPix(140), viewPix(50))];
        _alertView.hidden = YES;
    }
    return _alertView;
}


-(UIButton *)monthBtn{
    if(!_monthBtn){
        _monthBtn = [UIButton buttonWithTitle:@"" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#282828" selectColor:@"#282828"];
        _monthBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_monthBtn addTarget:self action:@selector(selecteMonthAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _monthBtn;
}

-(UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(300))];
        [self emptyViewWithSuperView:_footerView frame:_footerView.bounds];
    }
    return _footerView;
}

-(NSMutableArray *)openArray{
    if(!_openArray){
        _openArray = [NSMutableArray array];
    }
    return _openArray;
}


-(NSDateFormatter *)formatter1{
    if(!_formatter1){
        _formatter1 = [[NSDateFormatter alloc] init];
        _formatter1.dateFormat = @"YYYY年MM月";
    }
    return _formatter1;
}

-(NSDateFormatter *)formatter2{
    if(!_formatter2){
        _formatter2 = [[NSDateFormatter alloc] init];
        _formatter2.dateFormat = @"YYYY-MM";
    }
    return _formatter2;
}

@end
